import { LoginAPI, UserInfoAPI, LogOutAPI } from '@/apis/user'
import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'
import { getlocalStorage, setlocalStorage, removeItem } from '@/utils/localStorage'
import { Keys } from '@/utils/localStore_key' // token的键
import { routes , asyncRouter  , anyRouter} from '@/router/routesList'
import { type RouteRecordRaw } from 'vue-router'
import router from '@/router'
import { cloneDeep } from 'lodash'
interface userType {
  avatar?: string
  name?: string
}

// function filterAsyncRoute(asyncRouter: RouteRecordRaw[], routes: any) {
//  let RouteLists= asyncRouter.map((item:any) => {
//     if (routes.includes(item.name)) {
//       if (item.children && item.children.length > 0) {
//          item.children=filterAsyncRoute(item.children, routes)
//       }
//       return item
//     }
//   })
//   return RouteLists
// }

// 递归筛选用户有的路由
function filterAsyncRoute(asyncRouter: RouteRecordRaw[], routes: any) {
  return asyncRouter.filter((item:any) => {
     if (routes.includes(item.name)) {
       if (item.children && item.children.length > 0) {
          item.children=filterAsyncRoute(item.children, routes)
       }
       return true
     }
   })
 }

export const useUserStore = defineStore('user', () => {
  // 存储token
  const token = ref(getlocalStorage(Keys.TOKEN) || '')
  // 用户信息
  let UserInfos = ref<userType>({})

  //路由
  let RouterList:any= ref([])
  // 按钮权限
  let buttons=ref<string[]>([])

  // 设置token
  const setToken = (value: string) => {
    setlocalStorage(Keys.TOKEN, value)
    token.value = value
  }

  // 登录
  const login = async (data: any) => {
    let res: any = await LoginAPI(data)
    if (res.code == 200) {
      token.value = res.data
      setToken(res.data)
      return Promise.resolve(res)
    } else {
      return Promise.reject(new Error('账号或' + res.data))
    }
  }
  // 获取用户信息
  const getUserInfo = async () => {
    let res: any = await UserInfoAPI()
    // console.log(res, '用户')
    if (res.code == 200) {
      UserInfos.value = res.data
      // setlocalStorage(Keys.USERINFO,res.data)
      // console.log(UserInfos.value)

      // 深拷贝让新登录用户不影响菜单
      const UserRoutes=filterAsyncRoute(cloneDeep(asyncRouter),res.data.routes)
      // 把过滤好的动态路由注册到路由上
      UserRoutes.forEach((item)=>{
             router.addRoute(item)
      })
      router.addRoute(anyRouter)
      // 合并用户有的动态路由和静态路由
      RouterList.value=[...routes,...UserRoutes,anyRouter]
      // console.log(router.getRoutes());
      return 'ok'
    }
    return Promise.reject(new Error('token过期，请重新登录'))
  }

  // 退出登录
  const logout = async () => {
    let res = await LogOutAPI()
    if (res.code == 200) {
      removeItem(Keys.TOKEN)
      UserInfos.value = {}
      return 'ok'
    }
    return Promise.reject(new Error('退出登录失败'))
  }

  return { token, setToken, login, RouterList, getUserInfo, UserInfos, logout , buttons}
})
